package com.eesujie.xcs.util;

import com.eesujie.xcs.common.BusinessException;
import jakarta.annotation.PostConstruct;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


@Component
@ConfigurationProperties(prefix = "ip2region")
public class IPUtils {
    private String path;
    private byte[] buff;

    private String dbPath;

    @PostConstruct
    public void init() throws Exception {
        dbPath = Thread.currentThread().getContextClassLoader().getResource(path).getPath();
        buff = Searcher.loadVectorIndexFromFile(dbPath);
    }
    private static final int COUNTRY = 0;
    private static final int REGION = 1;
    private static final int PROVINCE = 2;
    private static final int CITY = 3;
    private static final int ISP = 4;

    // 格式：国家|区域|省份|城市|ISP

    public String getIpInfo(String ip) {
        try {
            Searcher searcher = Searcher.newWithVectorIndex(dbPath, buff);
            String region = searcher.search(ip);
            searcher.close();
            return region;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
    }

    public String getCountry(String ip) {
        return check(split(ip, COUNTRY));
    }

    public String getRegion(String ip) {
        return check(split(ip, REGION));
    }

    public String getProvince(String ip) {
        return check(split(ip, PROVINCE));
    }

    public String getCity(String ip) {
        return check(split(ip, CITY));
    }

    public String getISP(String ip) {
        return check(split(ip, ISP));
    }

    private String split(String ip, int index) {
        return getIpInfo(ip).split("\\|")[index];
    }

    private String check(String value) {
        return "0".equals(value) ? "未知" : value;
    }

    public void setPath(String path) {
        this.path = path;
    }
}
